package com.example.controller;

import cn.hutool.core.lang.Dict;
import com.example.dto.role.Role;
import com.example.dto.role.RoleCriteria;
import com.example.exception.BadRequestException;
import com.example.server.RoleServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "系统：角色管理")
@RequestMapping("/api/role")
public class RoleController {

    @Autowired
    private RoleServer roleServer;
    private static final String ENTITY_NAME = "role";

    @ApiOperation("获取单个role")
    @GetMapping(value = "/{id}")
    public ResponseEntity<Object> findRoleById(@PathVariable Long id){
        return new ResponseEntity<>(roleServer.findById(id), HttpStatus.OK);
    }
    @ApiOperation("返回全部的角色")
    @GetMapping(value = "/all")
    public ResponseEntity<Object> queryAllRole(){
        return new ResponseEntity<>(roleServer.findAll(),HttpStatus.OK);
    }

    @ApiOperation("获取用户级别")
    @GetMapping(value = "/level")
    public ResponseEntity<Object> getRoleLevel(){
        return new ResponseEntity<>(Dict.create().set("level", getLevels(null)), HttpStatus.OK);
    }

    /**
     * 获取用户的角色级别
     * @return /
     */
    private int getLevels(Integer level){
        Long userId = 1L;
        List<Integer> levels = roleServer.findByUsersId(userId).stream().map(Role::getLevel).collect(Collectors.toList());
        int min = Collections.min(levels);
        if(level != null){
            if(level < min){
                throw new BadRequestException("权限不足，你的角色级别：" + min + "，低于操作的角色级别：" + level);
            }
        }
        return min;
    }

    @ApiOperation("增加角色")
    @PostMapping
    public ResponseEntity<Object> add(@RequestBody Role resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        getLevels(resources.getLevel());
        roleServer.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @ApiOperation("删除角色")
    @DeleteMapping
    public ResponseEntity<Object> deleteRole(@RequestBody Set<Long> ids){
        for (Long id : ids) {
            Role role = roleServer.findById(id);
            getLevels(role.getLevel());
        }
        // 验证是否被用户关联
        roleServer.verification(ids);
        roleServer.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改角色")
    @PutMapping
    public ResponseEntity<Object> updateRole( @RequestBody Role resources){
        getLevels(resources.getLevel());
        roleServer.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @ApiOperation("修改角色菜单")
    @PutMapping(value = "/menu")
    public ResponseEntity<Object> updateRoleMenu(@RequestBody Role resources){
        Role role = roleServer.findById(resources.getId());
        getLevels(role.getLevel());
        roleServer.updateMenu(resources,role);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @ApiOperation("查询角色")
    @GetMapping
    public Map<String, Object> list(RoleCriteria roleCriteria) {
        Map<String, Object> result = new HashMap<>(4);
        result = roleServer.list(roleCriteria);
        return result;
    }
}
